package top.codef.secure.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.session.Session;
import org.springframework.session.data.redis.RedisIndexedSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

import top.codef.secure.config.delegates.CerberusSessionSecureConfig;

@Configuration
@ConditionalOnClass({ SpringSessionBackedSessionRegistry.class, RedisIndexedSessionRepository.class,
		RedisConnectionFactory.class })
@ConditionalOnProperty(value = "cerberus.secure.session.enable-redis-session-storage", havingValue = "true")
@AutoConfigureBefore({ CerberusSessionSecureConfig.class })
public class SessionRedisStorageConfig {

	private final Log logger = LogFactory.getLog(getClass());

	@Bean
	@ConditionalOnClass(SpringSessionBackedSessionRegistry.class)
	public SpringSessionBackedSessionRegistry<? extends Session> springSessionBackedSessionRegistry(
			RedisIndexedSessionRepository redisOperationsSessionRepository) {
		logger.info("配置session的redis存储");
		return new SpringSessionBackedSessionRegistry<>(redisOperationsSessionRepository);
	}

	@Bean
	RedisIndexedSessionRepository redisIndexedSessionRepository(RedisTemplate<String, Object> securityRedisTemplate) {
		return new RedisIndexedSessionRepository(securityRedisTemplate);
	}
}
